from lxml import html
import requests
import json
from user import User
from Comment import Comment
import re


class Mblog:
    # 定义构造方法

    def __init__(self, data):
        self.mblog = {}
        self.get_time(re.split('/', data['scheme'])[-1][:9])
        data = data['mblog']

        if 'longText' in data:
            self.mblog['content'] = data['longText']['longTextContent']
        else:
            self.mblog['content'] = data['text']
        tree = html.fromstring(self.mblog['content'])
        self.mblog['content'] = tree.xpath('string(.)')  # 用string函数过滤掉多余标签

        self.mblog['reposts_count'] = data['reposts_count']
        self.mblog['comments_count'] = data['comments_count']
        self.mblog['attitudes_count'] = data['attitudes_count']
        self.mblog['id'] = data['id']

        self.user = data['user']

        # try:
        #     self.mblog['category'] = data['longText']['url_objects'][0]['object']['object']['category']
        # except KeyError:
        #     self.mblog['category'] = '未归类'
        #     return

    # 默认获取前20条热评 可指定page页评论
    def get_time(self, id):
        url = 'https://m.weibo.cn/statuses/show?id=' + id
        res = requests.get(url)
        if res.status_code == 200:
            res = res.json()
            if res['ok'] == 1:
                self.mblog['created_at'] = res['data']['created_at']

    def get_comments(self, page=0):
        print(self.mblog['id'])
        if page == 0:
            url = 'https://m.weibo.cn/comments/hotflow?' + 'id=' + self.mblog['id'] + '&mid=' + self.mblog[
                'id'] + '&max_id_type=0'
        else:
            url = 'https://m.weibo.cn/api/comments/show?id=' + str(self.mblog['id']) + '&page=' + str(page)

        response = requests.get(url)
        comments = []
        if response.status_code == 200:
            ob_json = json.loads(response.text)
            # 评论获取成功
            if ob_json['ok'] == 1:
                list_comments = ob_json['data']['data']
                for item in list_comments:
                    comment = Comment(item)
                    comments.append(comment)
        return comments

    def get_user(self):
        return User(self.user)
